package me.jiatao.baselibrary.ui.activity

import android.os.Bundle
import me.jiatao.baselibrary.common.BaseApplication
import me.jiatao.baselibrary.injection.component.ActivityComponent
import me.jiatao.baselibrary.injection.component.DaggerActivityComponent
import me.jiatao.baselibrary.injection.module.ActivityModule
import me.jiatao.baselibrary.injection.module.LifecycleProviderModule
import me.jiatao.baselibrary.mvp.presenter.BasePresenter
import me.jiatao.baselibrary.mvp.view.BaseView
import me.jiatao.baselibrary.widgets.ProgressLoading
import javax.inject.Inject

/**
 * MVP框架中的Activity基类，与业务相关
 */
abstract class BaseMvpActivity<V : BaseView, P : BasePresenter<V>> : BaseActivity(), BaseView {
    @Inject
    lateinit var mPresenter: P
    lateinit var mActivityComponent: ActivityComponent
    private lateinit var mLoadingDialog: ProgressLoading

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initActivityInjection()
        injectComponent()

        //设置View引用
        @Suppress("UNCHECKED_CAST")
        mPresenter.attachView(this as V)

        //初始加载框
        mLoadingDialog = ProgressLoading.create(this)
    }

    override fun onDestroy() {
        mPresenter.detachView()
        super.onDestroy()
    }

    /**
     * 初始Activity Component
     */
    private fun initActivityInjection() {
        mActivityComponent = DaggerActivityComponent.builder()
            .appComponent((application as BaseApplication).appComponent)
            .activityModule(ActivityModule(this))
            .lifecycleProviderModule(LifecycleProviderModule(this))
            .build()
    }

    /**
     * 在子类中注入Component
     */
    protected abstract fun injectComponent()


    override fun showLoading() {
        mLoadingDialog.showLoading()
    }

    override fun hideLoading() {
        mLoadingDialog.hideLoading()
    }

    override fun onError(text: String) {
        showToast(text)
    }
}